package test;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class ListAllThreads {
	public static void main(String[] args) throws Exception {
		ThreadMXBean threadbean = ManagementFactory.getThreadMXBean();
		for (ThreadInfo info : getAllThreads(threadbean)) {
			System.out.printf("%4d - %s\n", info.getThreadId(), info.getThreadName());
		}
		RuntimeMXBean runtimebean = ManagementFactory.getRuntimeMXBean();
		System.out.println(getPid(runtimebean));
		Thread.sleep(Long.MAX_VALUE);
	}

	static ThreadInfo[] getAllThreads(ThreadMXBean threadbean) {
//		return threadbean.dumpAllThreads(false, false);
		return threadbean.getThreadInfo(threadbean.getAllThreadIds());
	}

	static String getPid(RuntimeMXBean runtimebean) {
		String vmname = runtimebean.getName();
		int i = vmname.indexOf('@');
		if (i != -1) {
			vmname = vmname.substring(0, i);
		}
		return vmname;
	}
}
